package it.tcm.TeacherClassMate.action;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import it.tcm.TeacherClassMate.beans.MailBean;
import it.tcm.TeacherClassMate.beans.UserBean;
import it.tcm.TeacherClassMate.facade.MailManageBase;
import it.tcm.TeacherClassMate.facade.UserManageBase;
import it.tcm.TeacherClassMate.form.CustomerForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


public class SendPasswordAction extends Action {

	// --------------------------------------------------------- Instance Variables

	// --------------------------------------------------------- Methods


	private Logger logger = Logger.getLogger(this.getClass().getName());
	private static DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
	
	/** 
	 * Method execute
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * 
	 */

	public ActionForward execute(
		ActionMapping mapping,
		ActionForm form,
		HttpServletRequest request,
		HttpServletResponse response) 
	{		
		 logger.info("SEND PASS ACTION");
		 CustomerForm mcaForm = (CustomerForm)form;			
		 String email = "";
		 if (mcaForm.getEmail() != null) { email = (String)mcaForm.getEmail();}
		 logger.info("email :" + email); 
		 //send mail
	     Date todayDate = new Date();		
		 UserManageBase usm = new UserManageBase();
		 List<UserBean> users = usm.getUserBeanByEmail(email.toLowerCase());
		 if (users != null && users.size() > 0)  {
			  UserBean user = users.get(0);
			  String body = "Recupero utenza www.verificafast.it per " + user.getName() + " " + user.getSurname() + " \n";
			  body = body + "Data: " + formatter.format(todayDate) + " \n";
			  body = body + "User: " + user.getUsername() + " \n";
			  body = body + "Password: " + user.getPassword() + " \n";	
			  try {
				MailBean mailBean = new MailBean();
				mailBean.setType("1");
				mailBean.setDest(email);
				mailBean.setBody(body);
				mailBean.setLock("0");
				mailBean.setSent("0");
				mailBean.setFailed(0);
				mailBean.setObject("Recupero utenza VerificaFast per  " + user.getName() + " " + user.getSurname());
				MailManageBase mmb = new MailManageBase();
				Integer i = mmb.save(mailBean);
				logger.info("mail with id " + i + " saved");
			 } catch (Exception e) {
						logger.error("Exception while saving mail : " + e);
			 }
		 } else {
			// la email non esiste sul database
			return mapping.findForward("nosendpwd"); 
		 }
		
		 return mapping.findForward("sendpwd"); 
		 
	}
	
	
}